package com.charlie.sessions;

import com.charlie.beans.Product;
import com.charlie.beans.ShipmentOrder;
import com.charlie.beans.SoHistory;
import com.charlie.beans.SoProduct;
import com.charlie.beans.Warehouse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Вова
 */
@Stateless
public class ShipmentOrderFacade extends AbstractFacade<ShipmentOrder> implements ShipmentOrderFacadeLocal {

    @PersistenceContext(unitName = "CharlieShop-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ShipmentOrderFacade() {
        super(ShipmentOrder.class);
    }

    @Override
    public ShipmentOrder createFromCart(CartLocal cart) {
        ShipmentOrder so = null;

        try {
            Warehouse wh = em.find(Warehouse.class, cart.getWarehouse());

            so = new ShipmentOrder();
            so.setEmail(cart.getEmail());
            so.setLocation(cart.getLocation());
            so.setWarehouseId(wh);
            so.setIsSubscribed((short) (cart.getNotify() ? 1 : 0));
            so.setCost(cart.getCost());
            so.setCreationDate(new Date());
            so.setDueDate(new Date());
            em.persist(so);

            List<SoProduct> items = new ArrayList<SoProduct>(cart.getItems().size());
            for (Cart.CartItem item : cart.getItems()) {
                try {
                    Product product = em.find(Product.class, item.getId());
                    SoProduct soProduct = new SoProduct();
                    soProduct.setAmount(item.getAmount());
                    soProduct.setProductId(product);
                    soProduct.setSoId(so);
                    items.add(soProduct);
                    em.persist(soProduct);
                } catch (NoResultException ex) {
                }
            }
            so.setSoProductCollection(items);
            em.merge(so);
        } catch (NoResultException ex) {
        }

        return so;
    }

    @Override
    public List<ShipmentOrder> findByStatus(Integer statusID, Integer from, Integer to) {
        List<ShipmentOrder> result = null;
        try {
            Query q;
            if (statusID == 1) {
                q = em.createQuery(" SELECT s FROM ShipmentOrder s "
                        + "WHERE NOT EXISTS (SELECT h FROM SoHistory h "
                        + "WHERE s.soId=h.soId.soId) ", ShipmentOrder.class);
            //    q.setFirstResult(from);
              //  q.setMaxResults(to);
            } else {
                q = em.createQuery("SELECT DISTINCT m.soId FROM SoHistory m "
                        + "WHERE m.soHistoryId IN ( SELECT  max(t.soHistoryId) FROM SoHistory t "
                        + "WHERE  t.statusDictId.statusDictId=?1 "
                        + "AND NOT EXISTS (SELECT  r FROM SoHistory r "
                        + "WHERE t.soId=r.soId AND t.statusDictId.statusDictId<r.statusDictId.statusDictId) "
                        + "GROUP BY t.soId) order by m.soHistoryId;", SoHistory.class);
                q.setParameter(1, statusID);
               // q.setFirstResult(from);
               // q.setMaxResults(to);
               
             }
            if (q.getResultList().size()>(to-from)&&(q.getResultList().size()>to)){
             result = q.getResultList().subList(from, to);}
            else {
                List r= q.getResultList(); 
                result =r.subList(from, r.size()); 
            }
            
            for (ShipmentOrder r : result) {
                em.refresh(r);
            }
            return result;

        } catch (NoResultException ex) {
            return result;
        }
    }

    @Override
    public int countByID(Integer id) {
        int result =0 ;  
        try {
        
        Query q;
            if (id == 1) {
                q = em.createQuery(" SELECT s FROM ShipmentOrder s "
                        + "WHERE NOT EXISTS (SELECT h FROM SoHistory h "
                        + "WHERE s.soId=h.soId.soId) ", ShipmentOrder.class);
            //    q.setFirstResult(from);
              //  q.setMaxResults(to);
            } else {
                q = em.createQuery("SELECT m.soId FROM SoHistory m "
                        + "WHERE m.soHistoryId IN ( SELECT  max(t.soHistoryId) FROM SoHistory t "
                        + "WHERE  t.statusDictId.statusDictId=?1 "
                        + "AND NOT EXISTS (SELECT  r FROM SoHistory r "
                        + "WHERE t.soId=r.soId AND t.statusDictId.statusDictId<r.statusDictId.statusDictId) "
                        + "GROUP BY t.soId) order by m.soHistoryId;", SoHistory.class);
                q.setParameter(1, id);
               
               
             }
            result=q.getResultList().size();
            return result; 

        } catch (NoResultException ex) {
            return result;
        }
    


   
}}
